package com.example.walkera.firstexoplayerdemo;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ConcatenatingMediaSource;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveVideoTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.MappingTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.PlaybackControlView;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;

/**
 * Created by lihaiping1603 on 2016/11/17.
 */

public class AVPlayerActivity extends Activity{

    //定义变量
    private static final String TAG="AVPlayerActivity";
    private Handler mainHandler;
//    private SimpleExoPlayerView simpleExoPlayerView;
    private AVPlayerView avplayerView;
    private SimpleExoPlayer avplayer=null;
    private MappingTrackSelector trackSelector;
    private boolean isTimeLineStatic=false;
    private int avplayerWindowIndex;//播放的窗口索引
    private long avplayerPosition;//播放的位置
    private boolean shouldAutoPlay=true;//是否自动播放
    private boolean avplayerNeedSource;//是否需要为播放器指定source源
    private Timeline.Window timelineWindow;

    private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        mainHandler= new Handler();
        timelineWindow= new Timeline.Window();

        /*给当前的activity加载一个xml布局文件*/
        setContentView(R.layout.activity_avplayer);

        //使用官方自带的simpleexoplayerview
//        simpleExoPlayerView=(SimpleExoPlayerView)findViewById(R.id.avplayer_simple_view);
//        simpleExoPlayerView.setControllerVisibilityListener(this);
//        simpleExoPlayerView.requestFocus();

        //使用自己写的avplayerview
        avplayerView=(AVPlayerView)findViewById(R.id.avplayer_frame_view);
        avplayerView.requestFocus();
        //实现控制面板一直显示出来
        avplayerView.setControllerShowTimeOutMs(0);

        Log.d(TAG, "onCreate: successful");
    }

    @Override
    public void onStart(){
        super.onStart();
        initializePlayer();
    }

    @Override
    public void onResume(){
        super.onResume();
        initializePlayer();
    }

    @Override
    public void onStop(){
        super.onStop();
        releasePlayer();
    }


    @Override
    public void onNewIntent(Intent intent){
        releasePlayer();
        isTimeLineStatic=false;
        setIntent(intent);
    }

   private void initializePlayer(){
       Intent intent=getIntent();

       if (avplayer==null) {//如果avplayer还没有初始化，就这里进行初始化
           // 1. Create a default TrackSelector
           TrackSelection.Factory videoTrackSelectionFactory= new AdaptiveVideoTrackSelection.Factory(BANDWIDTH_METER);

           trackSelector= new DefaultTrackSelector(mainHandler,videoTrackSelectionFactory);

           // 2. Create a default LoadControl
           LoadControl loadControl = new DefaultLoadControl();

           // 3. Create the player 创建一个exoplayer的实例
           avplayer= ExoPlayerFactory.newSimpleInstance(this,trackSelector,loadControl);

           //4.将player绑定到view上
           //simpleExoPlayerView.setPlayer(avplayer);
           avplayerView.setMediaAVPlayer(avplayer);

           if (isTimeLineStatic) {
                if (avplayerPosition== C.TIME_UNSET){
                    avplayer.seekToDefaultPosition(avplayerWindowIndex);
                }
               else{
                    avplayer.seekTo(avplayerWindowIndex,avplayerPosition);
                }
           }
           //5.设置播放器进入播放状态
           avplayer.setPlayWhenReady(shouldAutoPlay);
           //是否需要指定媒体源
           avplayerNeedSource=true;
           Log.d(TAG, "initializePlayer: setPlayer OK");
       }

       if (avplayerNeedSource){//如果需要媒体源source

           Uri[] uris=new Uri[]{intent.getData()};
           String userAgent=Util.getUserAgent(this,"firstExoPlayerDemo");
           //6..准备sources
           MediaSource[] mediaSources=new MediaSource[uris.length];
           for (int i=0;i<uris.length;i++)
           {
               // Produces DataSource instances through which media data is loaded.
               DataSource.Factory dataSourceFactory= new DefaultDataSourceFactory(this,userAgent);

               // Produces Extractor instances for parsing the media data.
               ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();

               // This is the MediaSource representing the media to be played.
               mediaSources[i] = new ExtractorMediaSource(uris[i], dataSourceFactory, extractorsFactory, null, null);
           }
            //对于只有一个url就用mediasources[0]，对于多个媒体source就连接多个媒体源ConcatenatingMediaSource
            MediaSource mediaSource=uris.length==1?mediaSources[0]:new ConcatenatingMediaSource(mediaSources);

           //7.准备播放,这时候如果已经setPlayWhenReady的话，就会进行数据回调了
           avplayer.prepare(mediaSource);

           avplayerNeedSource=false;
           Log.d(TAG, "initializePlayer: prepare OK");
       }
   }

    private void releasePlayer(){
        if (avplayer!=null){
            shouldAutoPlay=avplayer.getPlayWhenReady();
            avplayerWindowIndex=avplayer.getCurrentWindowIndex();
            avplayerPosition=C.TIME_UNSET;

            Timeline timeline=avplayer.getCurrentTimeline();
            if (timeline!=null&&timeline.getWindow(avplayerWindowIndex,timelineWindow).isSeekable){
                avplayerPosition=avplayer.getCurrentPosition();
            }
            avplayer.release();
            avplayer=null;
            trackSelector=null;
            Log.d(TAG, "releasePlayer: OK");
        }
    }

//    @Override
//    public void onLoadingChanged(boolean isloading) {
//        //暂时空白
//    }


//    @Override
//    public void onVisibilityChange(int visibility){
//
//    }
}
